<?php

class Admin_LoginController extends GTL_Action {

    public function init() {
        parent::init();
        $this->_helper->layout()->setLayout('admin-login');
        $this->sessionName = Zend_Registry::get('sessionName');
        $auth = Zend_Auth::getInstance();
        $this->view->LoggedIn = $auth->hasIdentity();
        $defaultSession = new Zend_Session_Namespace($this->sessionName);
        $defaultSessionVal = $defaultSession->getIterator();
        if (isset($defaultSessionVal['storage']) && !empty($defaultSessionVal['storage'])) {
            $this->view->user = $defaultSessionVal['storage'];
            $this->view->loggedinUserId = $this->view->user->usr_id;
            $this->_helper->redirector('index', 'index', 'admin');
        }
        /* Initialize action controller here */
    }

    public function indexAction() {
        #$loginForm = new Form_Admin_Login();
        $loginForm = new Form_Admin_Login();
        $this->view->form = $loginForm;
        $errorMessage = Array();

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (!$loginForm->isValid($postedData)) {
                $errorMessage = $loginForm->getMessages();
            } else {
                $auth = Zend_Auth::getInstance();
                $adapter = GTL_Common::getAuthAdapter($postedData, 'default');
                $result = $auth->authenticate($adapter);

                if ($result->isValid()) {

                    $auth->getStorage();
                    $objUser = $adapter->getResultRowObject();
                    /*
                      //User is of the type Admin
                      if ($objUser->lgn_type == '1') {
                      $adminObj = new Model_Admin();
                      $dataArray = Array();
                      $dataArray['lgn_id'] = $objUser->lgn_id;
                      $data = $adminObj->getAdminAuthData($dataArray);
                      } else if ($objUser->lgn_type == '2') {
                      //User is of the type Customer
                      $customerObj = new Model_Customer();
                      $dataArray = Array();
                      $dataArray['lgn_id'] = $objUser->lgn_id;
                      $data = $customerObj->getCustomerAuthData($dataArray);
                      } else if ($objUser->lgn_type == '3') {
                      //User is of the type Contractor
                      $contractorObj = new Model_Contractor();
                      $dataArray = Array();
                      $dataArray['lgn_id'] = $objUser->lgn_id;
                      $data = $contractorObj->getContractorAuthData($dataArray);
                      } else if ($objUser->lgn_type == '4') {
                      //User is of the type Designer
                      $designerObj = new Model_Designer();
                      $dataArray = Array();
                      $dataArray['lgn_id'] = $objUser->lgn_id;
                      $data = $designerObj->getDesignerAuthData($dataArray);
                      }

                     */
                    $auth->setStorage(new Zend_Auth_Storage_Session($this->sessionName));
                    $auth->getStorage()->write($objUser);
                    $this->_helper->redirector('index', 'index', 'admin');
                } else {
                    $loginForm->addErrorMessage("Username and Password do not match.");
                    $errorMessage['0'] = $loginForm->getErrorMessages();
                }
            }
        }
        $this->view->errorMessage = $errorMessage;
    }

    public function signupAction() {





        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $loginData = Array();
        $password = "";

        //Load login Model
        $loginModel = new Model_Login();

        //Load Customer Form
        $signUpForm = new Form_Admin_Signup();

        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();

            if (!$signUpForm->isValid($postedData)) {
                $errorMessage = $signUpForm->getMessages();

                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                //Check for the email exist while Adding custoemr
                $customerExist = $loginModel->checkEmailExist($postedData['email']);
                if ($customerExist) {
                    $errorMessageArray[] = "Email Address already exists!";
                }

                //Password Validation
                if ($postedData['password'] != "") {
                    if ($postedData['password'] != $postedData['user_confirmpassword']) {
                        $errorMessageArray[] = "Password and Confirm Password do not match each other.";
                    }
                }

                if (count($errorMessageArray) > 0) {
                    
                } else {


                    $password = md5($postedData['password']);
                    $loginData['lgn_name'] = $postedData['name'];
                    $loginData['lgn_phone'] = $postedData['phone'];
                    $loginData['lgn_email'] = $postedData['email'];
                    $loginData['lgn_password'] = $password;
                    $loginData['lgn_type'] = '1';
                    $loginData['lgn_created'] = date("Y-m-d H:i:s");
                    $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                    $loginData['lgn_active'] = '1';
                    $loginModel->save($loginData, 'lgn_id');

                    $loginLink = $this->view->BASE_URL . "admin/login";

                    $body = "
				<html>
				<head>
				</head>
				<body>
				<table style='width:50%'>
				    <tr>
				    <td>
				    <p>Hello " . $postedData['name'] . "</p>
                                    <p>Thanks for registration. You can login to the system via <a href='" . $loginLink . "'>Sign In</a></p>    
				    Thanks,<br/>
				    The Admin Team
				    </p>
				     </td>
				    </tr>
				</table>
				</body>
				</html>
				";

                    $metaDataModel = new Model_Metadata();
                    $ADMIN_MAIL_DATA = $metaDataModel->fetchEntryByKey("ADMIN_MAIL");
                    $ADMIN_MAIL = $ADMIN_MAIL_DATA['mtd_value'];

                    $mail = new Zend_Mail();
                    $mail->setBodyText($body);
                    $mail->setBodyHtml($body, "iso-8859-1");
                    $mail->addTo($ADMIN_MAIL, 'Instant Q&A Admin');
                    $mail->setReplyTo($ADMIN_MAIL, 'Instant Q&A Admin');
                    $mail->addTo($postedData['email'], 'Instant Q&A User');
                    $mailSubject = "Successfull Registration!";
                    $mail->addHeader('MIME-Version', '1.0');
                    $mail->addHeader('Content-Transfer-Encoding', '8bit');
                    $mail->addHeader('X-Mailer:', 'PHP/' . phpversion());
                    $mail->setSubject($mailSubject);

                    try {
                        $mail->send();
                        $successmessage = "Congratulations! You are registered successfully";
                        $signUpForm->reset();
                        $this->addSuccessMessage($successmessage);
                        $this->_helper->redirector('index', 'login', 'admin');
                    } catch (Zend_Exception $e) {
                        $errorMessageArray[] = "Due to technical problem, email has not been sent. Please try later or contact webmaster.";
                    }
                }
            }
        }

        $this->view->successmessage = $successmessage;
        $this->view->errorMessage = $errorMessageArray;
        $this->view->form = $signUpForm;
    }

    public function forgotpasswordAction() {

        $frgtPwdForm = new Form_Admin_Forgotpassword();
        $this->view->form = $frgtPwdForm;
        $errorMessage = Array();
        $successmessage = "";
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (!$frgtPwdForm->isValid($postedData)) {
                $errorMessage = $frgtPwdForm->getMessages();
            } else {
                $model = new Model_Login();
                $usrArray = $model->checkEmailForForgotPassword($postedData['email']);
                if (empty($usrArray) || $usrArray['lgn_id'] == '') {
                    $frgtPwdForm->addErrorMessage("Email address is not registered.");
                    $errorMessage['0'] = $frgtPwdForm->getErrorMessages();
                } else {
                    $actualPassword = GTL_Common::generatePassword(9, 2);
                    $md5_password = md5($actualPassword);
                    $body = "
				<html>
				<head>
				</head>
				<body>
				<table style='width:50%'>
				    <tr>
				    <td>
				    <p>Hello user</p>
				    <p>New password for your " . $this->config->SITE_NAME . " admin!</p>
				    <table border='1' cellpadding='10'>
					    <tr>
						    <td>Email Address</td>
						    <td width='80px' align='center'>" . $usrArray['lgn_email'] . "</td>
					    </tr>
					    <tr>
						    <td>Password</td>
						    <td>" . $actualPassword . "</td>
					    </tr>
				    </table>
				    <p>
				    Thanks,<br/>
				    The Admin Team
				    </p>
				     </td>
				    </tr>
				</table>
				</body>
				</html>
				";

                    $metaDataModel = new Model_Metadata();
                    $ADMIN_MAIL_DATA = $metaDataModel->fetchEntryByKey("ADMIN_MAIL");
                    $ADMIN_MAIL = $ADMIN_MAIL_DATA['mtd_value'];

                    $mail = new Zend_Mail();
                    $mail->setBodyText($body);
                    $mail->setBodyHtml($body, "iso-8859-1");
                    $mail->addTo($ADMIN_MAIL, 'Instant Q&A Admin');
                    $mail->setReplyTo($ADMIN_MAIL, 'Instant Q&A Admin');
                    $mail->addTo($usrArray['lgn_email'], 'Instant Q&A User');
                    $mailSubject = "Forgot Password Request";
                    $mail->addHeader('MIME-Version', '1.0');
                    $mail->addHeader('Content-Transfer-Encoding', '8bit');
                    $mail->addHeader('X-Mailer:', 'PHP/' . phpversion());
                    $mail->setSubject($mailSubject);

                    try {
                        $mail->send();
                        $dataUpdate = array();
                        $dataUpdate['lgn_id'] = $usrArray['lgn_id'];
                        $dataUpdate['lgn_password'] = $md5_password;
                        $model->save($dataUpdate, 'lgn_id');
                        $frgtPwdForm->reset();
                        $successmessage = "New password is sent to your email.";
                    } catch (Zend_Exception $e) {
                        $frgtPwdForm->addErrorMessage("Due to technical problem, email has not been sent. Please try later or contact webmaster.");
                        $errorMessage['0'] = $frgtPwdForm->getErrorMessages();
                    }
                    $frgtPwdForm->reset();
                }
            }
        }

        $this->view->successmessage = $successmessage;
        $this->view->errorMessage = $errorMessage;
    }

}

?>
